package com.mp.approvalreq.util;

import com.alibaba.fastjson.JSONArray;
import com.mp.approvalreq.entity.*;
import com.mp.user.entity.User;
import com.mp.user.service.UserServicePrx;
import com.plusmoney.util.Utils;
import com.qq.tars.client.util.ServantUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.*;
import java.util.stream.Collectors;

public class RequestUtils {

    private static final Logger logger = LoggerFactory.getLogger(RequestUtils.class);

    public static Map<Integer, Request> getRequestMap(List<Request> requests) {
        if (Utils.isEmpty(requests)) {
            return new HashMap<>();
        }
        return requests.stream().collect(Collectors.toMap(Request::getRequestDkey, request -> request, (a, b) -> b));
    }

    public static List<Integer> getRequestIds(List<Request> requests) {
        return requests.stream().map(Request::getRequestDkey).collect(Collectors.toList());
    }


    public static List<Integer> getTemplateIds(List<Request> requests) {
        return requests.stream().map(Template::getTemplateId).distinct().collect(Collectors.toList());
    }

    /**
     * 置顶红点
     *
     * @param requestIds  审批id
     * @param redPointMap 评论红点列表
     * @param redPointIds 抄送/参与红点列表
     */
    public static void stickyRedPoint(List<Integer> requestIds, Map<Integer, List<MessageRead>> redPointMap, List<Integer> redPointIds) {
        requestIds.sort((o1, o2) -> {
            if (redPointMap.containsKey(o1)) {
                if (existAtRedPoint(redPointMap.get(o1))) {
                    o1 = Integer.MAX_VALUE;
                } else {
                    o1 = Integer.MAX_VALUE - 1;
                }
            } else if (redPointIds.contains(o1)) {
                o1 = Integer.MAX_VALUE - 2;
            }


            if (redPointMap.containsKey(o2)) {
                if (existAtRedPoint(redPointMap.get(o2))) {
                    o2 = Integer.MAX_VALUE;
                } else {
                    o2 = Integer.MAX_VALUE - 1;
                }
            } else if (redPointIds.contains(o2)) {
                o2 = Integer.MAX_VALUE - 2;
            }
            return o2 - o1;
        });
    }

    private static boolean existAtRedPoint(List<MessageRead> messageReads) {
        return messageReads.stream().anyMatch(msg -> msg.getIsAtRed() == 1);
    }

    /**
     * 分页
     *
     * @param query
     * @param list
     * @param <T>
     * @return
     */
    public static <T> List<T> paging(Query query, List<T> list) {
        if (Utils.isNull(query.getDataNum())) {
            query.setDataNum(20);
        }
        int totalCount = list.size();
        int begin = (query.getPage() - 1) * query.getDataNum();
        if (totalCount <= begin) {
            return new ArrayList<>();
        } else {
            return list.subList(begin, begin + Math.min(totalCount - begin, query.getDataNum()));
        }
    }

    /**
     * 设置红点
     *
     * @param list
     * @param redPointMap
     */
    public static void setRedPoint(List<Request> list, Map<Integer, List<MessageRead>> redPointMap) {
        for (Request request : list) {
            if (!redPointMap.containsKey(request.getRequestDkey())) {
                continue;
            }
            List<MessageRead> messageReads = redPointMap.get(request.getRequestDkey());
            request.setCommentCount(messageReads.size());
            for (MessageRead messageRead : messageReads) {
                if (messageRead.getIsRefuse() > 0) {
                    request.setRefuseRedPoint(1);
                }
                if (messageRead.getIsAtRed() > 0) {
                    request.setAtRedPoint(1);
                }
            }
        }
    }

    /**
     * 设置红点(抄送/参与)
     *
     * @param redPointIds
     * @param list
     */
    public static void setRedPoint(List<Integer> redPointIds, List<Request> list) {
        if (Utils.isEmpty(redPointIds)) {
            return;
        }
        for (Request request : list) {
            if (redPointIds.contains(request.getRequestDkey())) {
                request.setCcUnRead(1);
                request.setRedPoint(1);
            }
        }
    }

    /**
     * 排序
     *
     * @param list
     * @param orderBy 0.默认智能排序（置顶红点）; 1.按创建时间排序; 2.按最后批准的时间排序; 3.按最后归档时间排序
     */
    public static void sort(List<Request> list, String orderBy) {
        try {
            if (StringUtils.isBlank(orderBy) || "0".equals(orderBy)) {
                sortByRedPoint(list);
            }
        } catch (Throwable e) {
            logger.error(e.getMessage(), e);
            EmailUtils.sendMail("排序出错", e);
        }
    }

    /**
     * 智能排序
     *
     * @param requestList
     */
    private static void sortByRedPoint(List<Request> requestList) {
        requestList.sort((o1, o2) -> {
            int l1 = o1.getRequestDkey(), l2 = o2.getRequestDkey();
            if (Objects.equals(o1.getAtRedPoint(), 1)) {
                l1 = Integer.MAX_VALUE;
            } else if (Objects.equals(o1.getRefuseRedPoint(), 1)) {
                l1 = Integer.MAX_VALUE - 1;
            } else if (o1.getCommentCount() > 0) {
                l1 = Integer.MAX_VALUE - 2;
            } else if (Objects.equals(o1.getCcUnRead(), 1)) {
                l1 = Integer.MAX_VALUE - 3;
            }


            if (Objects.equals(o2.getAtRedPoint(), 1)) {
                l2 = Integer.MAX_VALUE;
            } else if (Objects.equals(o2.getRefuseRedPoint(), 1)) {
                l2 = Integer.MAX_VALUE - 1;
            } else if (o2.getCommentCount() > 0) {
                l2 = Integer.MAX_VALUE - 2;
            } else if (Objects.equals(o2.getCcUnRead(), 1)) {
                l2 = Integer.MAX_VALUE - 3;
            }
            return l2 - l1;
        });
    }

    public static void setTemplateInfo(List<Request> requests, Map<Integer, Template> templateMap) {
        if (Utils.isEmpty(requests) || Utils.isEmpty(templateMap)) {
            return;
        }
        for (Request request : requests) {
            if (!templateMap.containsKey(request.getTemplateId())) {
                continue;
            }
            Template template = templateMap.get(request.getTemplateId());
            request.setTemplateName(template.getTemplateName());
            request.setTemplateComponent(template.getTemplateComponent());
            request.setTemplateColor(template.getTemplateColor());
            request.setDefaultType(template.getDefaultType());
            request.setPriorityShow(template.getPriorityShow());
        }
    }

    public static void setComponentInfo(List<Request> requests, Map<Integer, List<TemplateComponent>> componentMap,
                                        Map<Integer, Map<Integer, List<GroupContent>>> groupComponentMap) {
        if (Utils.isEmpty(requests) || Utils.isEmpty(componentMap)) {
            return;
        }
        for (Request request : requests) {
            if (!componentMap.containsKey(request.getRequestDkey())) {
                continue;
            }
            List<TemplateComponent> components = componentMap.get(request.getRequestDkey());
            List<TemplateComponent> templateComponents = JSONArray.parseArray(request.getTemplateComponent(), TemplateComponent.class);
            Map<Integer, List<GroupContent>> groupContentMap = groupComponentMap.get(request.getRequestDkey());

            List<TemplateComponent> mergeComponents = ComponentUtils.mergeComponents(templateComponents, components, groupContentMap);
            request.setTemplateComponent(JSONArray.toJSONString(mergeComponents));
            //用于更新模板内容
            request.setComponentsContent(mergeComponents);
        }
    }

    public static Map<Integer, User> getRequestUserMap(Request request, Template template) throws Throwable {
        Set<Integer> set = new HashSet<>();
        set.add(request.getApplicant());
        if (Utils.isNotNull(request.getProxyContactId()) && request.getProxyContactId() > 0) {
            set.add(request.getProxyContactId());
        }
        if (StringUtils.isNotEmpty(request.getRelaPeople())) {
            set.addAll(Utils.string2list(request.getRelaPeople()));
        }
        if (StringUtils.isNotEmpty(template.getCc())) {
            List<String> list = ListHelper.string2StringList(template.getCc());
            set.addAll(list.stream().filter(ValidateUtil::isInteger).map(Integer::parseInt).collect(Collectors.toSet()));
        }
        if (StringUtils.isNotEmpty(request.getCcTemp())) {
            set.addAll(Utils.string2list(request.getCcTemp()));
        }
        if (Utils.isNotEmpty(request.getCcList())) {
            set.addAll(request.getCcList().stream().map(Cc::getCcId).collect(Collectors.toSet()));
        }
        logger.info("开始获取用户信息:{}", set);
        UserServicePrx userServicePrx = ServantUtils.getObject(UserServicePrx.class);
        List<User> userList = userServicePrx.getUserListByContactIds(Utils.collection2string(set));

        return userList.stream().collect(Collectors.toMap(User::getContactId, user -> user, (a, b) -> b));
    }
}
